package com.pro.addresslist.ui.activity;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.sqllite.ContactInfoServise;
import com.pro.addresslist.tools.BASE64Encrypt;
import com.pro.addresslist.tools.NetUtil;
import com.pro.addresslist.tools.runNumber;
import com.pro.addresslist.ui.adapter.CommonAdapter;
import com.pro.addresslist.ui.adapter.ViewHolder;
import com.pro.addresslist.ui.common.BaseActivity;
import com.pro.addresslist.ui.view.PopMenu;


/**
 * 新建联系人
 * leekh'，20161215，xml文件加入水平线,增加修改为本地数据库。
 * 20161219.更新选择地域不显示问题，改变titlt
 * @author admin
 * 
 */
public class NewContactsActivity extends BaseActivity {



	private List<Object[]> listitm = new ArrayList<Object[]>();
	private List<Object[]> listitmm = new ArrayList<Object[]>();
	private List<Object[]> listNexus = new ArrayList<Object[]>();
	private List<Object[]> listNexus1 = new ArrayList<Object[]>();
	private List<Object[]> listNexus2 = new ArrayList<Object[]>();
	private PopMenu pop;
	private PopMenu popp;
	private PopMenu poppp;
	private static ImageButton ibAddPhone;// 添加手机的图标
	private TextView tvlinear;// 水平线
	private SimpleAdapter phone;
	private List<String> list = new ArrayList<String>();
	private ListView gr;
	private int height = 50;
	CommonAdapter<String> test;
	private ImageButton btnDelete;// 删除按钮
	private ImageButton btnEdit;// 编辑按钮
	private EditText etName;// 姓名
	private RadioGroup rgSex;// 性别
	private RadioButton rbMale;// 男
	private RadioButton rbFemale;// 女
	private EditText etNationality;// 民族
	private EditText etUnit;// 单位
	private EditText etDepartment;// 部门
	private EditText etPost;// 职务
	private EditText etBirthday = null;// 生日
	private EditText etMobile;// 手机
	private ListView lvphone;// 添加多个手机号显示在ListView中
	private Button bntdy; // 地域
	private Button bntgk; // 归口
	private EditText etInterest;// 兴趣爱好
	private EditText etFood;// 饮食偏好
	private EditText etDepartTell;// 单位电话
	private EditText etDepartAddress;// 单位地址
	private EditText etFamilyTell;// 家庭电话
	private EditText etAddress;// 家庭地址
	private EditText etOtherTell;// 其他电话
	private EditText etDepict;// 明细
	private TextView diatitle;

	// 生日控件编写
	private static final int SHOW_DATAPICK = 0;
	private static final int DATE_DIALOG_ID = 1;
	private static final int SHOW_TIMEPICK = 2;
	private static final int TIME_DIALOG_ID = 3;
	private int mYear;
	private int mMonth;
	private int mDay;
	private String int_action = "addcon";
	private static int Upid=0;//本地id
	private static String UpConId= "";
	//广播
	private ReceiveBroadCast receiveBroadCast;
	private IntentFilter filter;
	@Override
	public int getLayout() {

		//return R.layout.activity_new_contacts;
		return R.layout.activity_addcontacts;

	}

	void inintview() {
		etName = (EditText) findViewById(R.id.etName);// 姓名
		rgSex = (RadioGroup) findViewById(R.id.rgSex);// 性别
		rbMale = (RadioButton) findViewById(R.id.rbMale);// 男
		rbFemale = (RadioButton) findViewById(R.id.rbFemale);// 女
		etNationality = (EditText) findViewById(R.id.etNationality);// 民族
		etUnit = (EditText) findViewById(R.id.etUnit);// 单位
		etDepartment = (EditText) findViewById(R.id.etDepartment);// 部门
		etPost = (EditText) findViewById(R.id.etPost);// 职务
		etBirthday = (EditText) findViewById(R.id.etBirthday);// 生日
		etMobile = (EditText) findViewById(R.id.etMobile);// 手机
		lvphone = (ListView) findViewById(R.id.lvphone);// 添加多个手机号显示在ListView中
		etInterest = (EditText) findViewById(R.id.etInterest);// 兴趣爱好
		etFood = (EditText) findViewById(R.id.etFood);// 饮食偏好
		etDepartTell = (EditText) findViewById(R.id.etDepartTell);// 单位电话
		etDepartAddress = (EditText) findViewById(R.id.etDepartAddress);// 单位地址
		etFamilyTell = (EditText) findViewById(R.id.etFamilyTell);// 家庭电话
		etAddress = (EditText) findViewById(R.id.etAddress);// 家庭地址
		etOtherTell = (EditText) findViewById(R.id.etOtherTell);// 其他电话
		etDepict = (EditText) findViewById(R.id.etDepict);// 明细.
		ibAddPhone = (ImageButton) findViewById(R.id.ibAddPhone);
		ibAddPhone.setOnClickListener(this);

		// 这里手机格式化输出
		etMobile.addTextChangedListener(new MyTextWatcher(etMobile));

	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		setTtile("新建联系人");
		// setLeftIamge(, listener)
		setLeftImageBack();
		inintview();
		UIActionlode();
		setRightText("保存",this);
		setViewClick(R.id.tv_title_right_text);// 保存点击事件
		
		
		Intent int_i = this.getIntent();
		int_action = int_i.getStringExtra("actions");

		if (int_action != null) {
			if (int_action.contains("edtcon")) {
				setTtile("编辑联系人");
				int_action = "edtcon";
				// 查询一个id
				int conid = int_i.getIntExtra("conid",1);
				Upid = conid;
				//ContactInfoBLL bll = new ContactInfoBLL();
				//bll.SelectContactByID(getApplicationContext(), conid);
				ContactInfoServise ser = new ContactInfoServise(getApplicationContext());
				//danren
			List<ContactInfoBySqlite> lists = new ArrayList<ContactInfoBySqlite>(); 
			
			lists=ser.SelectContactByID(conid);
			ShowEditDate(lists.get(0));
			
			} else if (int_action.contains("saomiao")) {
				ContactInfo con = (ContactInfo) int_i
						.getSerializableExtra("saomiao");
				// 做显示
				ShowData(con);
			} else {
				int_action = "addcon";
			}
		} else {
			int_action = "addcon";
		}	
	}

	// 名片显示
	private void ShowData(ContactInfo con) {
		etName.setText(con.get_Name());
		etUnit.setText(con.get_Unit());
		etPost.setText(con.get_Post());
		etMobile.setText(con.get_Mobile());
		etFamilyTell.setText(con.get_FamilyTell());
		etDepartTell.setText(con.get_DepartTell());// no en
		etDepartAddress.setText(con.get_DepartAddress());
	}

	public class ReceiveBroadCast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			String res = intent.getStringExtra("parameter");
			if (action.equals("lbs_AddContact")) {
				if (res.equals("succeed")) {
					Integer ID=(Integer) intent.getSerializableExtra("id");
					ContactInfoServise ser = new ContactInfoServise(getApplicationContext());
					ser.UpdataContactStateByID(ID, 0);
					finish();
				}
				else {
					Builder dia = new AlertDialog.Builder(NewContactsActivity.this)   
					.setMessage("该联系人上传失败，是否转到上传页面？")  
					.setPositiveButton("是" ,  new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							 Toast.makeText(mContext, "请点击上传按钮！", Toast.LENGTH_LONG).show();
							 Intent synchronize = new Intent();
								synchronize.setClass(getApplicationContext(),
										SynchronizeActivity.class);
								startActivity(synchronize);
						}
					} )  
					.setNegativeButton("否" , new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}) ; 
					dia.show();
				}
			} 
			if (action.equals("lbs_UpdataContact")) {
				if (res.equals("succeed")) {
					ContactInfoServise ser = new ContactInfoServise(getApplicationContext());
					Integer ID=(Integer) intent.getSerializableExtra("id");
					ser.UpdataContactStateByID(ID, 0);
					finish();
				}
				else {
					Builder dia = new AlertDialog.Builder(NewContactsActivity.this)   
					.setMessage("该联系人上传失败，是否转到上传页面？")  
					.setPositiveButton("是" ,  new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							 Toast.makeText(mContext, "请点击上传按钮！", Toast.LENGTH_LONG).show();
							 Intent synchronize = new Intent();
								synchronize.setClass(getApplicationContext(),
										SynchronizeActivity.class);
								startActivity(synchronize);
						}
					} )  
					.setNegativeButton("否" , new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}) ; 
					dia.show();
				}
			} 
//			else if (action.equals("lbs_SelectContactByID")) {
//				ContactInfo con = (ContactInfo) intent
//						.getSerializableExtra("parameter");
//				if (con != null) {
//					// 查到id做显显示
//					Upid= con.get_ContactID();
//					etName.setText("" + con.get_Name());
//					// 0,man
//					if (con.get_Sex() != 0) {
//						rbFemale.setChecked(true);// 女
//					} else {
//						rbMale.setChecked(true);
//					}
//					etNationality.setText("" + con.get_Nationality());
//					etUnit.setText("" + con.get_Unit());
//					etDepartment.setText("" + con.get_Department());
//					etPost.setText("" + con.get_Post());
//					etBirthday.setText("" + con.get_Birthday());
//					bntdy.setText("" + con.get_dy());
//					bntgk.setText("" + con.get_gk());
//					// etMobile.setText("" + con.get_MobileEn());
//					String nuph = con.get_MobileEn().trim();
//					String[] nuphs = nuph.split(",");
//					if (nuphs.length <= 1) {
//						etMobile.setText("" + con.get_MobileEn());
//					} else {
//						etMobile.setText("" + nuphs[0].toString());
//						for (int i = 1; i < nuphs.length; i++) {
//							String txtPhone = nuphs[i].toString();
//							if (txtPhone == " " || txtPhone == null
//									|| txtPhone.length() <= 0) {
//								return;
//							}
//							list.add(txtPhone.trim());
//							test.notifyDataSetChanged();
//							LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) gr
//									.getLayoutParams(); // 取控件textView当前的布局参数
//							linearParams.height += height;// 强制设置控件的高
//							linearParams.leftMargin = 14;
//							gr.setLayoutParams(linearParams);
//							tvlinear.setVisibility(View.VISIBLE);
//						}
//					}
//
//					etInterest.setText("" + con.get_Interest());
//					etFood.setText("" + con.get_Food());
//					etDepartTell.setText("" + con.get_DepartTell());// no en
//					etDepartAddress.setText("" + con.get_DepartAddress());
//					etFamilyTell.setText("" + con.get_FamilyTell());
//					etAddress.setText("" + con.get_Address());
//					etOtherTell.setText("" + con.get_OtherTell());
//					etDepict.setText("" + con.get_Depict());
//				}
//			}

		}
	}

	/**
	 * SomeLodeCode
	 */
	private void UIActionlode() {
		// 地域
		bntdy = (Button) findViewById(R.id.bntdy);
		bntdy.setOnClickListener(this);
		listitm.add(new Object[] { "上海" });
		listitm.add(new Object[] { "昆明" });
		listitm.add(new Object[] { "北京" });
		listitmm.add(new Object[] { "武汉" });
		listitmm.add(new Object[] { "南京" });
		listitmm.add(new Object[] { "北京" });
		listitmm.add(new Object[] { "武汉" });
		listitmm.add(new Object[] { "南京" });
		listitmm.add(new Object[] { "北京" });

		bntgk = (Button) findViewById(R.id.bntgk);
		bntgk.setOnClickListener(this);
		listNexus.add(new Object[] { "内部关系" });
		listNexus.add(new Object[] { "外部关系" });
		listNexus1.add(new Object[] { "集团" });
		listNexus1.add(new Object[] { "云工商" });
		listNexus1.add(new Object[] { "贵工商" });
		listNexus1.add(new Object[] { "华德" });
		listNexus2.add(new Object[] { "团" });

		// 生日
		initializeViews();
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR); // 年
		mMonth = c.get(Calendar.MONTH); // 月
		mDay = c.get(Calendar.DAY_OF_MONTH);// 日
		// 添加手机号码

		// 水平线
		tvlinear = (TextView) findViewById(R.id.tvlinear);
		// 删除
		btnDelete = (ImageButton) findViewById(R.id.btnDelete);
		// 编辑
		btnEdit = (ImageButton) findViewById(R.id.btnEdit);
		// btnEdit.setOnClickListener(this);
		// 获取对话框中的值
		gr = (ListView) findViewById(R.id.lvphone);
		test = new CommonAdapter<String>(NewContactsActivity.this, list,
				R.layout.activity_lvphone) {

			@Override
			public void convert(ViewHolder holder, String t) {
				// TODO Auto-generated method stub
				holder.setText(R.id.textPhone, t);
				final int position = holder.getPosition();
				// 编辑手机号
				holder.setOnClickListener(R.id.btnEdit, new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						LayoutInflater factory1 = LayoutInflater
								.from(NewContactsActivity.this);
						// 获取对话框中的EditText控件中的值
						final View textEntryView1 = factory1.inflate(
								R.layout.activity_phone, null);
						final EditText etPhone1 = (EditText) textEntryView1
								.findViewById(R.id.etphone);
						etPhone1.addTextChangedListener(new MyTextWatcher(
								etPhone1));// 限制输入格式

						// 获取ListView中的值
						final View textEntryView2 = factory1.inflate(
								R.layout.activity_lvphone, null);
						final TextView etPhone2 = (TextView) textEntryView2
								.findViewById(R.id.textPhone);
						String txtPhone1 = list.get(position);
						etPhone1.setText(txtPhone1);
						AlertDialog.Builder add1 = new AlertDialog.Builder(
								NewContactsActivity.this);
						
						add1.setTitle("添加手机号:");
						add1.setView(textEntryView1);
						add1.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int i) {
										String txtPhone3 = etPhone1.getText()
												.toString();
										list.set(position, txtPhone3);
										test.notifyDataSetChanged();
										LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) gr
												.getLayoutParams(); // 取控件textView当前的布局参数
										linearParams.height += height;// 强制设置控件的高
										linearParams.leftMargin = 14;
										gr.setLayoutParams(linearParams);
									}
								});
						add1.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int i) {
									}
								});
						add1.show();// 显示对话框
					}
				});

				// 删除手机号
				holder.setOnClickListener(R.id.btnDelete,
						new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								new AlertDialog.Builder(
										NewContactsActivity.this)
										.setTitle("系统消息")
										.setMessage("确定要删除该号码？")
										.setNegativeButton("取消", null)
										.setPositiveButton(
												"确定",
												new DialogInterface.OnClickListener() {
													@Override
													public void onClick(
															DialogInterface dialog,
															int which) {
														list.remove(list
																.get(position));
														test.notifyDataSetChanged();
													}
												})
										.setNegativeButton("取消", null).show();
							}
						});
			}
		};
		gr.setAdapter(test);
	}

	@SuppressLint("NewApi") @Override
	public void OnViewClick(View v) {

		
		
		switch (v.getId()) {
		// //添加手机号码
		case R.id.ibAddPhone:
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.activity_phone,
					null);
			final EditText etPhone = (EditText) textEntryView
					.findViewById(R.id.etphone);
			etPhone.addTextChangedListener(new MyTextWatcher(etPhone));// 限制输入格式
			final Builder ad1 = new AlertDialog.Builder(this,R.style.my_dialog);  
			
			
			ad1.setTitle("添加手机号:");
			
			ad1.setView(textEntryView);
			ad1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					String txtPhone = etPhone.getText().toString();
					if (txtPhone == " " || txtPhone == null
							|| txtPhone.length() <= 0) {
						return;
					}
					list.add(txtPhone.trim());
					test.notifyDataSetChanged();
					LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) gr
							.getLayoutParams(); // 取控件textView当前的布局参数
					linearParams.height += height;// 强制设置控件的高
					linearParams.leftMargin = 14;
					gr.setLayoutParams(linearParams);
					tvlinear.setVisibility(View.VISIBLE);

				}
			});
			ad1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
				}
			});
			AlertDialog dialogsAlertDialog=ad1.create();
			dialogsAlertDialog.show();
			
			 
			//ad1.show();// 显示对话框
			NewContactsActivity.dialogTitleLineColor(dialogsAlertDialog, R.color.color_prompt1);
			break;
		// 地区
		case R.id.bntdy:
			if(!NetUtil.isNetworkAvailable(getApplicationContext())){
				Toast.makeText(getApplicationContext(), "亲！ 没有网络！一会再选吧",Toast.LENGTH_SHORT).show();
				return;
			}
			// pop = new PopMenu(NewContactsActivity.this, R.layout.test,
			// R.id.listv, R.layout.test_itmes, listitm, R.id.d1, 0, 300);
			// pop.showAsDropDown(bntdy, 0, 0, true);
			Intent int_select = new Intent();
			
			int_select
					.setClass(getApplicationContext(), externalActivity.class);
			int_select.putExtra("action", "dy");
			int_select.putExtra("name", "地域关系");
			startActivityForResult(int_select, 0);

			break;
		// 归口
		case R.id.bntgk:
			if(!NetUtil.isNetworkAvailable(getApplicationContext())){
				Toast.makeText(getApplicationContext(), "亲！ 没有网络！一会再选吧",Toast.LENGTH_SHORT).show();
				return;
			}
			Intent int_selects = new Intent();
			int_selects.setClass(getApplicationContext(),
					externalActivity.class);
			int_selects.putExtra("action", "gk");
			int_selects.putExtra("name", "关系归口");
			startActivityForResult(int_selects, 1);
			break;
		// 保存
		case R.id.tv_title_right_text:
			if (etName.getText().toString().length() <= 0) {
				Toast.makeText(NewContactsActivity.this, "联系人姓名不能为空！",
						Toast.LENGTH_SHORT).show();
				break;
			}

			if (etMobile.getText().toString().trim().length() <= 0) {
				Toast.makeText(NewContactsActivity.this, "联系人手机号不能为空！",
						Toast.LENGTH_SHORT).show();
				break;
			}
			ContactInfoBySqlite con = new ContactInfoBySqlite();
			con.set_Name(etName.getText().toString());// 姓名 //
			if (rbMale.isChecked()) {
				con.set_Sex(0);// male
			} else {
				con.set_Sex(1);// nv
			}
			con.set_Nationality(etNationality.getText().toString());// 民族
			con.set_Unit(etUnit.getText().toString());// 单位
			con.set_Department(etDepartment.getText().toString());// 部门
			con.set_Post(etPost.getText().toString());// 职务
			con.set_Birthday(etBirthday.getText().toString());// 生日
			con.set_dy(bntdy.getText().toString());// 地域
			con.set_gk(bntgk.getText().toString()); // 关系归口

			String mp = etMobile.getText().toString().replace(" ", "")+",";// ！！去空格
			if (list.size() > 0) {
			//	mp = mp + ",";
				for (int i = 0; i < list.size(); i++) {
					mp += list.get(i).trim() + ",";
				}
			}
			mp = mp.trim().substring(0, mp.length() - 1).replace(" ", "");					
			Log.i("bt", "phonenumber-->" + mp.replace(" ", ""));
			mp = BASE64Encrypt.encryptCode(mp);//加密保存
			
			Log.i("bt", "phonenumber-->" + mp.replace(" ", ""));
			con.set_Mobile(mp);// 手机
			con.set_Interest(etInterest.getText().toString());// 兴趣爱好
			con.set_Food(etFood.getText().toString());// 饮食偏好
			con.set_DepartTell(etDepartTell.getText().toString());// 单位电话
			con.set_DepartAddress(etDepartAddress.getText().toString());// 单位地址
			con.set_FamilyTell(etFamilyTell.getText().toString());// 家庭电话
			con.set_Address(etAddress.getText().toString());// 家庭地址
			con.set_OtherTell(etOtherTell.getText().toString());// 其他电话
			con.set_Depict(etDepict.getText().toString());// 明细
			ContactInfoBLL bll = new ContactInfoBLL();
			if (int_action.contains("edtcon")) {
				con.set_id(Upid);
				con.set_ContactID(UpConId);
			//	bll.UpdataContact(getApplicationContext(), con,1);				
				ContactInfoServise ser = new ContactInfoServise(getApplicationContext());
				ser.UpdataContact(con);
				Toast.makeText(getApplicationContext(), "联系修改成功！",
						Toast.LENGTH_SHORT).show();
				if(NetUtil.isNetworkAvailable(mContext)){
					ContactInfo coninfo = writeModel(con);
					ContactInfoBLL.UpdataContact(mContext, coninfo,con.get_id());
				}
				else {
					Toast.makeText(getApplicationContext(), "当前没有网络，请及时上传联系人！",Toast.LENGTH_SHORT).show();
					finish();
				}
			} else {
				runNumber run = new runNumber();
				con.set_ContactID(run.getMaxID());//生成随机id。
				Log.i("bt", "添加联系人+>>>"+"联系人id"+con.get_ContactID());
				ContactInfoServise ser = new ContactInfoServise(getApplicationContext());
				ser.AddContact(con);
				Toast.makeText(getApplicationContext(), "联系人添加成功！",
						Toast.LENGTH_SHORT).show();
				if(NetUtil.isNetworkAvailable(mContext)){
					ContactInfo coninfo = writeModel(con);
					ContactInfoBLL.AddContact(mContext, coninfo,con.get_id());
					ser.UpdataContactStateByConID(con.get_ContactID(), 0);
				}
				else {
					Toast.makeText(getApplicationContext(), "当前没有网络，请及时上传联系人！",Toast.LENGTH_SHORT).show();
					finish();
				}
			}

			break;
		default:
			break;
		}
	}
	@SuppressLint("ResourceAsColor") public static final void dialogTitleLineColor(Dialog dialog, int colors) {  
	    Context context = dialog.getContext();  
	    int divierId = context.getResources().getIdentifier("android:id/titleDivider", null, null);  
	    View divider = dialog.findViewById(divierId);  
	    divider.setBackgroundColor(colors);  
	    divider.setBackgroundResource(R.drawable.show_head_toast_bg);
	}  
	// 初始化控件和UI视图
	private void initializeViews() {
		etBirthday = (EditText) findViewById(R.id.etBirthday);// 生日
		etBirthday.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Message msg = new Message();
				if (etBirthday.equals((EditText) v)) {
					msg.what = NewContactsActivity.SHOW_DATAPICK;
				}
				NewContactsActivity.this.dateandtimeHandler.sendMessage(msg);
			}
		});
	}

	// 设置日期
	private void setDateTime() {
		final Calendar c = Calendar.getInstance();

		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		updateDateDisplay();
	}

	// 更新日期显示
	private void updateDateDisplay() {
		etBirthday.setText(new StringBuilder().append(mYear).append("-")
				.append((mMonth + 1) < 10 ? "0" + (mMonth + 1) : (mMonth + 1))
				.append("-").append((mDay < 10) ? "0" + mDay : mDay));
	}

	// 日期控件的事件
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;

			updateDateDisplay();
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}

		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	// 处理日期和时间控件的Handler
	Handler dateandtimeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NewContactsActivity.SHOW_DATAPICK:
				showDialog(DATE_DIALOG_ID);
				break;
			case NewContactsActivity.SHOW_TIMEPICK:
				showDialog(TIME_DIALOG_ID);
				break;
			}
		}

	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(data != null){
		Bundle b = data.getExtras(); // data为B中回传的Intent
		String str = b.getString("relation");// str即为回传的值
		
			switch (requestCode) {
			case 0:
				bntdy.setText(str.trim());
				break;
			case 1:
				bntgk.setText(str.trim());
				break;
			default:
				break;
			}
		}
		
	}

	public static class MyTextWatcher implements TextWatcher {

		private EditText phoneNumberEditText;
		String tmp;

		int start, count, beforeSelectionStart;

		public MyTextWatcher(EditText numberEditText) {
			this.phoneNumberEditText = numberEditText;
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			System.out
					.println("onTextChanged ---- start = " + start
							+ " before = " + before + " count = " + count
							+ "  s= " + s);
			this.start = start;
			this.count = count;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			beforeSelectionStart = phoneNumberEditText.getSelectionStart();
			System.out.println("beforeTextChanged getSelectionStart="
					+ phoneNumberEditText.getSelectionStart());
			System.out.println("beforeTextChanged ---- start = " + start
					+ " count = " + count + " after = " + after + "  s= " + s);
		}

		@Override
		public void afterTextChanged(Editable s) {
			System.out.println("---afterTextChanged---");

			// char c = '-';//' '; //修改分割值.
			char c = ' ';
			String sourceStr = s.toString();
			if (tmp != null && tmp.equals(sourceStr)) {
				return;
			}
			tmp = separateString(sourceStr, 3, 4, c);
			if (!tmp.equals(sourceStr)) {
				phoneNumberEditText.setText(tmp);
				System.out.println("start = " + start + " s.length = "
						+ s.length() + " count = " + count);
				if (start == 0) {
					if (s.length() == (count - 1)) {
						phoneNumberEditText.setSelection(tmp.length());
					} else if (s.length() == count) {
						phoneNumberEditText.setSelection(beforeSelectionStart);
					}
				}
				// phoneNumberEditText.setSelection(tmp.length());
			}
			// 这里处理添加手机按钮的显示和隐藏
			if (phoneNumberEditText.length() <= 0) {
				ibAddPhone.setVisibility(View.INVISIBLE);
			} else {
				ibAddPhone.setVisibility(View.VISIBLE);
			}
		}

		/**
		 * 用指定字符分隔格式化字符串 ，自己修改传入参数。 <br/>
		 * （如电话号为1391235678 指定startIndex为3，step为4，separator为'-'经过此处理后的结果为 <br/>
		 * 139-1234-5678）
		 * 
		 * @param source
		 *            需要分隔的字符串
		 * @param startIndex
		 *            开始分隔的索引号
		 * @param step
		 *            步长
		 * @param separator
		 *            指定的分隔符
		 * @return 返回分隔格式化处理后的结果字符串
		 */
		private String separateString(String source, int startIndex, int step,
				char separator) {
			int times = 0;
			StringBuilder tmpBuilder = new StringBuilder(source);
			for (int i = 0; i < tmpBuilder.length(); i++) {
				if (i == startIndex + step * times + times) {// if(i == 3 || i
																// == 8){
					if (separator != tmpBuilder.charAt(i)) {
						tmpBuilder.insert(i, separator);
					}
					times++;
				} else {
					if (separator == tmpBuilder.charAt(i)) {
						tmpBuilder.deleteCharAt(i);
						i = -1;
						times = 0;
					}
				}
			}
			return tmpBuilder.toString();
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		//注册广播
		 receiveBroadCast = new ReceiveBroadCast();
		 filter = new IntentFilter();
		filter.addAction("lbs_AddContact");
		filter.addAction("lbs_UpdataContact");
//		filter.addAction("lbs_SelectContactByID");
		registerReceiver(receiveBroadCast, filter);
	}
	//查询联系人做显示，编辑界面的接收
	private void ShowEditDate(ContactInfoBySqlite con){
			
			if (con != null) {
				// 查到id做显显示
				Upid= con.get_id();
				UpConId = con.get_ContactID();
				etName.setText(con.get_Name());
				// 0,man
				if (con.get_Sex() != 0) {
					rbFemale.setChecked(true);// 女
				} else {
					rbMale.setChecked(true);
				}
				etNationality.setText( con.get_Nationality());
				etUnit.setText(con.get_Unit());
				etDepartment.setText(con.get_Department());
				etPost.setText(con.get_Post());
				etBirthday.setText(con.get_Birthday());
				bntdy.setText( con.get_dy());
				bntgk.setText(con.get_gk());
				// etMobile.setText("" + con.get_MobileEn());
				String nuph = con.get_MobileEn().trim();
				String[] nuphs = nuph.split(",");
				if (nuphs.length <= 1) {
					etMobile.setText(con.get_MobileEn());
				} else {
					etMobile.setText(nuphs[0].toString());
					for (int i = 1; i < nuphs.length; i++) {
						String txtPhone = nuphs[i].toString();
						if (txtPhone == " " || txtPhone == null
								|| txtPhone.length() <= 0) {
							return;
						}
						list.add(txtPhone.trim());
						test.notifyDataSetChanged();
						LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) gr
								.getLayoutParams(); // 取控件textView当前的布局参数
						linearParams.height += height;// 强制设置控件的高
						linearParams.leftMargin = 14;
						gr.setLayoutParams(linearParams);
						tvlinear.setVisibility(View.VISIBLE);
					}
				}

				etInterest.setText( con.get_Interest());
				etFood.setText(con.get_Food());
				etDepartTell.setText( con.get_DepartTell());// no en
				etDepartAddress.setText(con.get_DepartAddress());
				etFamilyTell.setText( con.get_FamilyTell());
				etAddress.setText(con.get_Address());
				etOtherTell.setText( con.get_OtherTell());
				etDepict.setText(con.get_Depict());
				
				
			}
		}
		

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		/*if(receiveBroadCast!= null){
			unregisterReceiver(receiveBroadCast);
		}*/
	}
	//转化实体
	private ContactInfo writeModel(ContactInfoBySqlite con) {
		ContactInfo coninfo=new ContactInfo();
		coninfo.set_Address(con.get_Address()==null?"":con.get_Address());
		coninfo.set_Birthday(con.get_Birthday()==null?"":con.get_Birthday());
		coninfo.set_ContactID(con.get_ContactID()==null?"":con.get_ContactID());
		coninfo.set_DepartAddress(con.get_DepartAddress()==null?"":con.get_DepartAddress());
		coninfo.set_Department(con.get_Department()==null?"":con.get_Department());
		coninfo.set_DepartTell(con.get_DepartTell()==null?"":con.get_DepartTell());
		coninfo.set_Depict(con.get_Depict()==null?"":con.get_Depict());
		coninfo.set_dy(con.get_dy()==null?"":con.get_dy());
		coninfo.set_gk(con.get_gk()==null?"":con.get_gk());
		coninfo.set_FamilyTell(con.get_FamilyTell()==null?"":con.get_FamilyTell());
		coninfo.set_Food(con.get_Food()==null?"":con.get_Food());
		coninfo.set_HeadImage(con.get_HeadImage()==null?"":con.get_HeadImage());
		coninfo.set_Interest(con.get_Interest()==null?"":con.get_Interest());
		coninfo.set_Mobile(con.get_Mobile()==null?"":con.get_MobileEn());
		coninfo.set_Name(con.get_Name()==null?"":con.get_Name());
		coninfo.set_Nationality(con.get_Nationality()==null?"":con.get_Nationality());
		coninfo.set_OtherTell(con.get_OtherTell()==null?"":con.get_OtherTell());
		coninfo.set_Post(con.get_Post()==null?"":con.get_Post());
		coninfo.set_Unit(con.get_Unit()==null?"":con.get_Unit());
		coninfo.set_Sex(con.get_Sex());
		return coninfo;
	}
}
